package cn.yuznu.www;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.sql.*;

public class ChatClient extends JFrame {
    private TextArea ta = new TextArea();
    private TextField tf = new TextField();
    private Socket s = null;
    private DataOutputStream dos = null;
    private DataInputStream dis = null;
    private String username;

    public void launchFrame() throws Exception {
        this.add(ta, BorderLayout.CENTER);
        this.add(tf, BorderLayout.SOUTH);
        tf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                try {
                    String sSend = tf.getText();
                    if (sSend.trim().length() == 0) return;
                    send(sSend);
                    tf.setText("");
                    ta.append(username + ": " + sSend + "\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                System.exit(0);
            }
        });
        setBounds(300, 300, 300, 400);
        setVisible(true);
        tf.requestFocus();
    }

    public ChatClient() throws Exception {
        s = new Socket("127.0.0.1", 8888);
        launchFrame();
        (new Thread(new ReceiveThread())).start();
        showLoginDialog();
    }

    private void showLoginDialog() {
        String[] options = {"登录", "注册"};
        int n = JOptionPane.showOptionDialog(null, "您想要登录还是注册？", "聊天客户端",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (n == 0) { // 登录
            login();
        } else if (n == 1) { // 注册
            register();
        }
    }

    private void login() {
        String username = JOptionPane.showInputDialog("请输入您的用户名:");
        String password = JOptionPane.showInputDialog("请输入您的密码:");
        try {
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
            dos.writeUTF("LOGIN");
            dos.writeUTF(username);
            dos.writeUTF(password);
            String response = dis.readUTF();
            if ("LOGIN_SUCCESS".equals(response)) {
                this.username = username;
                JOptionPane.showMessageDialog(null, "登录成功。");
            } else {
                JOptionPane.showMessageDialog(null, "登录失败。请重试或注册。");
                showLoginDialog();
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "无法连接到服务器: " + e.getMessage());
            System.exit(1);
        }
    }

    private void register() {
        String username = JOptionPane.showInputDialog("请输入新用户名:");
        String password = JOptionPane.showInputDialog("请输入新密码:");
        try {
            dos = new DataOutputStream(s.getOutputStream());
            dos.writeUTF("REGISTER");
            dos.writeUTF(username);
            dos.writeUTF(password);
            String response = dis.readUTF();
            if ("REGISTER_SUCCESS".equals(response)) {
                JOptionPane.showMessageDialog(null, "注册成功。请登录。");
                showLoginDialog();
            } else {
                JOptionPane.showMessageDialog(null, "注册失败。");
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "无法连接到服务器: " + e.getMessage());
            System.exit(1);
        }
    }

    public void send(String str) throws Exception {
        dos.writeUTF(str);
    }

    public void disconnect() throws Exception {
        s.close();
    }

    class ReceiveThread implements Runnable {
        public void run() {
            if (s == null) return;
            try {
                String str = dis.readUTF();
                while (str != null) {
                    ta.append(str + "\n");
                    str = dis.readUTF();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new ChatClient();
    }
}